package com.sxr.webflux;

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * 安全文件处理器
 * 提供基于WebFlux函数式编程的文件访问接口
 * 
 * @author SXR
 * @since 1.0.0
 */
public class SecureFileHandler {
    
    private final ReactiveFileService reactiveFileService;
    
    public SecureFileHandler(ReactiveFileService reactiveFileService) {
        this.reactiveFileService = reactiveFileService;
    }
    
    /**
     * 处理文件下载请求
     */
    public HandlerFunction<ServerResponse> download() {
        return request -> {
            return reactiveFileService.handleSecureDownload(
                    request.exchange().getRequest(),
                    request.exchange().getResponse()
            ).then(ServerResponse.ok().build())
            .onErrorResume(throwable -> 
                ServerResponse.status(500)
                    .contentType(MediaType.APPLICATION_JSON)
                    .bodyValue("{\"success\":false,\"error\":\"" + 
                              escapeJson(throwable.getMessage()) + "\"}")
            );
        };
    }
    
    /**
     * 处理文件预览请求
     */
    public HandlerFunction<ServerResponse> preview() {
        return request -> {
            return reactiveFileService.handleSecurePreview(
                    request.exchange().getRequest(),
                    request.exchange().getResponse()
            ).then(ServerResponse.ok().build())
            .onErrorResume(throwable -> 
                ServerResponse.status(500)
                    .contentType(MediaType.APPLICATION_JSON)
                    .bodyValue("{\"success\":false,\"error\":\"" + 
                              escapeJson(throwable.getMessage()) + "\"}")
            );
        };
    }
    

    
    /**
     * 健康检查
     */
    public HandlerFunction<ServerResponse> health() {
        return request -> {
            return reactiveFileService.healthCheck(
                    request.exchange().getRequest(),
                    request.exchange().getResponse()
            ).then(ServerResponse.ok().build())
            .onErrorResume(throwable -> 
                ServerResponse.status(500)
                    .contentType(MediaType.APPLICATION_JSON)
                    .bodyValue("{\"success\":false,\"error\":\"" + 
                              escapeJson(throwable.getMessage()) + "\"}")
            );
        };
    }
    
    /**
     * JSON字符串转义
     */
    private String escapeJson(String str) {
        if (str == null) {
            return "";
        }
        return str.replace("\"", "\\\"")
                  .replace("\\", "\\\\")
                  .replace("\n", "\\n")
                  .replace("\r", "\\r")
                  .replace("\t", "\\t");
    }
}
